<template>
  <div class="user-list-view">
    <!-- 搜索和操作栏 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          v-model="searchQuery"
          type="text" 
          placeholder="搜索用户..."
          class="search-input"
          @input="handleSearch"
        />
        <button class="search-button">
          <i class="icon-search"></i>
        </button>
      </div>
      
      <div class="action-buttons">
        <button 
          class="btn primary"
          @click="openCreateDialog"
        >
          <i class="icon-add"></i> 添加用户
        </button>
        <button 
          class="btn secondary"
          @click="exportToCSV"
        >
          <i class="icon-download"></i> 导出
        </button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-container">
      <table class="user-table">
        <thead>
          <tr>
            <th @click="sortUsers('id')">
              用户ID
              <i :class="['sort-icon', sortConfig.key === 'id' ? 'active' : '']">
                {{ sortConfig.direction === 'asc' ? '↑' : '↓' }}
              </i>
            </th>
            <th @click="sortUsers('name')">
              姓名
              <i :class="['sort-icon', sortConfig.key === 'name' ? 'active' : '']">
                {{ sortConfig.direction === 'asc' ? '↑' : '↓' }}
              </i>
            </th>
            <th>头像</th>
            <th>邮箱</th>
            <th>角色</th>
            <th @click="sortUsers('status')">
              状态
              <i :class="['sort-icon', sortConfig.key === 'status' ? 'active' : '']">
                {{ sortConfig.direction === 'asc' ? '↑' : '↓' }}
              </i>
            </th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="!loading">
          <tr v-for="user in paginatedUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.name }}</td>
            <td>
              <img :src="user.avatar" :alt="user.name" class="user-avatar" />
            </td>
            <td>{{ user.email }}</td>
            <td>
              <span :class="['role-badge', user.role.toLowerCase()]">
                {{ user.role }}
              </span>
            </td>
            <td>
              <span :class="['status-badge', user.status.toLowerCase()]">
                {{ user.status }}
              </span>
            </td>
            <td class="actions">
              <button 
                class="icon-button edit"
                @click="editUser(user.id)"
                title="编辑"
              >
                <i class="icon-edit"></i>
              </button>
              <button 
                class="icon-button view"
                @click="viewUser(user.id)"
                title="查看详情"
              >
                <i class="icon-eye"></i>
              </button>
              <button 
                class="icon-button delete"
                @click="confirmDelete(user.id)"
                title="删除"
              >
                <i class="icon-delete"></i>
              </button>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="7" class="loading-cell">
              <div class="loading-spinner"></div>
              正在加载用户数据...
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination">
      <button 
        class="pagination-button"
        :disabled="currentPage === 1"
        @click="currentPage = 1"
      >
        首页
      </button>
      <button 
        class="pagination-button"
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        上一页
      </button>
      
      <div class="page-numbers">
        <button 
          v-for="page in visiblePages" 
          :key="page"
          class="page-number"
          :class="{ active: currentPage === page }"
          @click="currentPage = page"
        >
          {{ page }}
        </button>
        <span v-if="totalPages > 5 && currentPage < totalPages - 2" class="ellipsis">...</span>
      </div>
      
      <button 
        class="pagination-button"
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        下一页
      </button>
      <button 
        class="pagination-button"
        :disabled="currentPage === totalPages"
        @click="currentPage = totalPages"
      >
        末页
      </button>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 用户数据
const users = ref([]);
const filteredUsers = ref([]);
const loading = ref(true);
const searchQuery = ref('');
const showCreateDialog = ref(false);

// 分页配置
const currentPage = ref(1);
const itemsPerPage = ref(10);

// 排序配置
const sortConfig = ref({
  key: 'id',
  direction: 'asc'
});

// 模拟API获取用户数据
const fetchUsers = () => {
  loading.value = true;
  
  // 模拟API延迟
  setTimeout(() => {
    users.value = [
      { id: 1, name: '张三', avatar: '/images/avatars/user1.jpg', email: 'zhangsan@example.com', role: '管理员', status: '活跃' },
      { id: 2, name: '李四', avatar: '/images/avatars/user2.jpg', email: 'lisi@example.com', role: '编辑', status: '活跃' },
      { id: 3, name: '王五', avatar: '/images/avatars/user3.jpg', email: 'wangwu@example.com', role: '用户', status: '禁用' },
      { id: 4, name: '赵六', avatar: '/images/avatars/user4.jpg', email: 'zhaoliu@example.com', role: '管理员', status: '活跃' },
      { id: 5, name: '钱七', avatar: '/images/avatars/user5.jpg', email: 'qianqi@example.com', role: '用户', status: '待激活' },
      { id: 6, name: '孙八', avatar: '/images/avatars/user6.jpg', email: 'sunba@example.com', role: '编辑', status: '活跃' },
      { id: 7, name: '周九', avatar: '/images/avatars/user7.jpg', email: 'zhoujiu@example.com', role: '用户', status: '活跃' },
      { id: 8, name: '吴十', avatar: '/images/avatars/user8.jpg', email: 'wushi@example.com', role: '用户', status: '禁用' },
      { id: 9, name: '郑十一', avatar: '/images/avatars/user9.jpg', email: 'zhengshiyi@example.com', role: '编辑', status: '活跃' },
      { id: 10, name: '王十二', avatar: '/images/avatars/user10.jpg', email: 'wangshier@example.com', role: '管理员', status: '待激活' }
    ];
    
    filteredUsers.value = [...users.value];
    loading.value = false;
  }, 800);
};

// 搜索处理
const handleSearch = () => {
  if (!searchQuery.value) {
    filteredUsers.value = [...users.value];
    return;
  }
  
  const query = searchQuery.value.toLowerCase();
  filteredUsers.value = users.value.filter(user => 
    user.name.toLowerCase().includes(query) || 
    user.email.toLowerCase().includes(query) ||
    user.role.toLowerCase().includes(query)
  );
  
  currentPage.value = 1;
};

// 排序用户
const sortUsers = (key) => {
  if (sortConfig.value.key === key) {
    sortConfig.value.direction = sortConfig.value.direction === 'asc' ? 'desc' : 'asc';
  } else {
    sortConfig.value.key = key;
    sortConfig.value.direction = 'asc';
  }
  
  filteredUsers.value.sort((a, b) => {
    const valueA = a[key].toString().toLowerCase();
    const valueB = b[key].toString().toLowerCase();
    
    if (valueA < valueB) {
      return sortConfig.value.direction === 'asc' ? -1 : 1;
    }
    if (valueA > valueB) {
      return sortConfig.value.direction === 'asc' ? 1 : -1;
    }
    return 0;
  });
};

// 分页计算
const totalPages = computed(() => {
  return Math.ceil(filteredUsers.value.length / itemsPerPage.value);
});

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  return filteredUsers.value.slice(start, end);
});

const visiblePages = computed(() => {
  const pages = [];
  const maxVisible = 5;
  
  let start = Math.max(1, currentPage.value - 2);
  let end = Math.min(totalPages.value, start + maxVisible - 1);
  
  if (end - start < maxVisible - 1) {
    start = Math.max(1, end - maxVisible + 1);
  }
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  
  return pages;
});

// 用户操作
const openCreateDialog = () => {
  showCreateDialog.value = true;
};

const editUser = (id) => {
  router.push({ name: 'user-edit', params: { id } });
};

const viewUser = (id) => {
  router.push({ name: 'user-detail', params: { id } });
};

const confirmDelete = (id) => {
  if (confirm('确定要删除这个用户吗？此操作不可撤销。')) {
    // 实际项目中调用API删除
    filteredUsers.value = filteredUsers.value.filter(user => user.id !== id);
    users.value = users.value.filter(user => user.id !== id);
  }
};

const exportToCSV = () => {
  // CSV导出逻辑
  alert('导出功能将在实际项目中实现');
};

// 生命周期钩子
onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-list-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-input {
  padding: 10px 15px;
  border: none;
  width: 300px;
  outline: none;
  font-size: 16px;
}

.search-button {
  padding: 10px 15px;
  background: #42b983;
  color: white;
  border: none;
  cursor: pointer;
  transition: background 0.3s;
}

.search-button:hover {
  background: #3498db;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 10px 15px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: 500;
  transition: all 0.3s;
}

.btn.primary {
  background: #42b983;
  color: white;
}

.btn.primary:hover {
  background: #3498db;
}

.btn.secondary {
  background: #f0f0f0;
  color: #333;
}

.btn.secondary:hover {
  background: #e0e0e0;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th {
  background: #f8f9fa;
  padding: 15px;
  text-align: left;
  font-weight: 600;
  color: #2c3e50;
  border-bottom: 2px solid #eee;
  cursor: pointer;
  position: relative;
}

.user-table th:hover {
  background: #f0f2f5;
}

.sort-icon {
  margin-left: 5px;
  font-style: normal;
  opacity: 0.5;
}

.sort-icon.active {
  opacity: 1;
  color: #42b983;
}

.user-table td {
  padding: 15px;
  border-bottom: 1px solid #eee;
  color: #555;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.role-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.admin {
  background: #e8f4ff;
  color: #3498db;
}

.role-badge.editor {
  background: #fff8e6;
  color: #f39c12;
}

.role-badge.user {
  background: #f0f5ff;
  color: #9b59b6;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.活跃 {
  background: #e8f6f0;
  color: #27ae60;
}

.status-badge.禁用 {
  background: #fdeded;
  color: #e74c3c;
}

.status-badge.待激活 {
  background: #fef9e7;
  color: #f39c12;
}

.actions {
  display: flex;
  gap: 8px;
}

.icon-button {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s;
}

.icon-button.edit {
  color: #3498db;
}

.icon-button.edit:hover {
  background: #e8f4ff;
}

.icon-button.view {
  color: #9b59b6;
}

.icon-button.view:hover {
  background: #f0f5ff;
}

.icon-button.delete {
  color: #e74c3c;
}

.icon-button.delete:hover {
  background: #fdeded;
}

.loading-cell {
  text-align: center;
  padding: 40px !important;
  color: #7f8c8d;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #42b983;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

.pagination-button {
  padding: 8px 16px;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-button:not(:disabled):hover {
  background: #42b983;
  color: white;
  border-color: #42b983;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.page-number {
  min-width: 36px;
  padding: 8px;
  text-align: center;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-number.active {
  background: #42b983;
  color: white;
  border-color: #42b983;
}

.page-number:not(.active):hover {
  background: #e0f0e9;
}

.ellipsis {
  padding: 8px;
}
</style>